package com.yan.utils;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;


public class MapUtils {

    public static <T> Map<String, Object> bean2Map(Object object) throws Exception {
        Map<String, Object> result = new HashMap<String, Object>();
        if (object == null) {
            return result;
        }
        @SuppressWarnings("unchecked")
        Class<T> cls = (Class<T>) object.getClass();
        Field[] fields = cls.getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);//类中的成员变量为private,故必须进行此操作,否则异常
            if (field.getName().equalsIgnoreCase("serialVersionUID")) {
                continue;
            }
            result.put(field.getName(), field.get(object));
        }
        return result;
    }

    public static <T> Object map2Bean(Map<String, Object> map, Class<T> cls) throws Exception {
        Object object = cls.newInstance();
        for (String key : map.keySet()) {
            Field temFiels = cls.getDeclaredField(key);
            temFiels.setAccessible(true);
            temFiels.set(object, map.get(key));
        }
        return object;
    }


}
